<?php

class Birthdayrem_Widget_HomeReminderController extends Engine_Content_Widget_Abstract
{
  public function indexAction()
  {
    try {
      $viewer = Engine_Api::_()->user()->getViewer();
      if ( !$viewer->getIdentity() ) {
        $this->setNoRender();
      }
      
      $field = Engine_Api::_()->fields()->getFieldsMeta('user')->getRowsMatching('alias', 'birthdate');
      $table = Engine_Api::_()->fields()->getTable('user', 'values');
      $select = $table->select()
        ->where("DAY(value) = DAY(NOW()) AND MONTH(value) = MONTH(NOW())")
        ->where("field_id = ".$field[0]['field_id']);
      
      if ( $this->_getParam('type', 1) ) {
        $select = $viewer->membership()->getMembersOfSelect();
        $friends = Zend_Paginator::factory($select);  
    
        // Get stuff
        $ids = array();
        foreach( $friends as $friend ) {
          $ids[] = $friend->resource_id;
        }
        
        $select->where("item_id IN (".implode(',', $ids).")");
      }
      
      $select->order("rand()");
      if ( $this->_getParam('limit', null) ) $select->limit((int)$this->_getParam('limit'));
      
      $birthdates = $table->fetchAll($select);
      
      $users = array();
      foreach ( $birthdates as $birthdate ) {
        $users[] = Engine_Api::_()->user()->getUser($birthdate->item_id);
      }
      if ( !count($users) ) {
        $this->setNoRender();
      }
      $this->view->users = $users;
    }
    catch ( Exception $e ) {
      echo $e->getMessage();
    }

  }
}